package com.leyou.privilege.interceptors;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.privilege.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
public class PrivilegeInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties prop;

    public PrivilegeInterceptor(JwtProperties prop) {
        this.prop = prop;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        try {
            //获取请求头中的tolen
            String token = request.getHeader(prop.getApp().getHeaderName());
            //校验token，解析数据
            Payload<AppInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), AppInfo.class);
            //获取访问方的身份
            AppInfo appInfo = payload.getUserInfo();
            Long id = appInfo.getId();
            String name = appInfo.getServiceName();
            log.info("服务：{} - {} 正在发起请求。",id,name);
            return true;
        } catch (Exception e) {
            log.error("非法访问，token解析失败",e);
            return false;
        }
    }
}
